# Author: Michal 'mucha' Muszynski
# License: MIT

package TinyURL;
use base Module;
use strict;
use LWP::Simple;
use HTML::Entities;

my $urllength = Config::get('urllength', '100');

# Encode all non-word characters into hex representations
sub encode_url
{
	my $url = $_[0];
	$url =~ s/([\W])/"%" . uc(sprintf("%2.2x",ord($1)))/eg;
	return $url;
}

sub shorten
{
	my $url = shift;
	if ($url =~ /(http:\/\/\S+)/) {
		my $tiny = get("http://42.pl/u/?auto=1&url=" . encode_url($1));

		return $tiny;
	}
}

sub on_public
{
	my $text = $_[1];

	if ($text =~ /(http:\/\/\S+)/) {
		my $link = $1;
		if (length($link) > $urllength) {
			my $tiny = shorten($link);
			Core::send_msg(Util::bold("[TinyURL] ") . $tiny);
		}
	}
}
